1772D - Absolute Sorting - CodeForces Solution


constructive algorithms math *1400

Please click on ads to support us..

Python Code:

from math import ceil
def sorting_value(nums, x = 0):

    if sorted(nums) == nums: return x
    if sorted(nums, reverse= True) == nums: return nums[0] + 1

    x = []
    for i in range(1,len(nums)):
        if nums[i - 1] > nums[i]:
            x += [ceil ((nums[i - 1] + nums[i]) / 2)]

    
    x = max(x)
    sorted_nums = [abs (num - x) for num in nums]

    if sorted(sorted_nums) == sorted_nums: return x

    return -1

if __name__ == "__main__":
    for _ in range(int(input())):
        input()
        nums = [int(x) for x in input().split()]

        value = sorting_value(nums)
        print (value)

C++ Code:

#include <bits/stdc++.h>
 
using namespace std;

int main()
{
    int t;
    cin >> t;
    for(int i = 0; i < t; i++)
    {
        int n;
        cin >> n;
        vector<int> a(n);
        for(int j = 0; j < n; j++)
            cin >> a[j];
        int mn = 0, mx = int(1e9);
        for(int j = 0; j + 1 < n; j++)
        {
            int x = a[j];
            int y = a[j + 1];
            int midL = (x + y) / 2;
            int midR = (x + y + 1) / 2;
            if(x < y)
                mx = min(mx, midL);
            if(x > y)
                mn = max(mn, midR);
        }
        if(mn <= mx) cout << mn << endl;
        else cout << -1 << endl;
    }
}


Comments

Submit
0 Comments
More Questions

Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making